package com.example.first;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

public class RateActivity extends AppCompatActivity implements Runnable{
    private static final String TAG="Rate";
    float dollarrate=0.1577f;
    float eurorate=0.142f;
    float wonrate=191.3949f;
    Handler handler;
    EditText input;
    TextView show;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate);
//加载之前设定的汇率数据
        Timer timer = new Timer();
        timer.schedule(new TimerTask(){
            @Override
            public void run(){
                Intent intent = new Intent(RateActivity.this,RateActivity.class);
                startActivity(intent);
            }
        },86400000);
        Log.i(TAG, "onCreate: 更新。。。");
        SharedPreferences sharedPreferences=getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        dollarrate=sharedPreferences.getFloat("dollar_rate",0.15f);
        eurorate=sharedPreferences.getFloat("euro_rate",0.14f);
        wonrate=sharedPreferences.getFloat("won_rate",191.39f);
        Thread t = new Thread(this);
            t.start();
            show = findViewById(R.id.tw1);
            handler = new Handler(Looper.myLooper()) {
                @Override
                public void handleMessage(@NonNull Message msg) {
                    if (msg.what == 5) {
                        Bundle bundle = (Bundle) msg.obj;
                        dollarrate = bundle.getFloat("web-dollar");
                        eurorate = bundle.getFloat("web-euro");
                        wonrate = bundle.getFloat("web-won");
                        Log.i(TAG, "handleMessage: dollar:" + dollarrate);
                        Log.i(TAG, "handleMessage: euro:" + eurorate);
                        Log.i(TAG, "handleMessage: won:" + wonrate);
                        Toast.makeText(RateActivity.this, "已更新汇率", Toast.LENGTH_SHORT).show();
                    }
                    super.handleMessage(msg);
                }
            };
    }
    public void click(View btn){
        Log.i(TAG,"click:");
        input = findViewById(R.id.result);
        String s = input.getText().toString();
        if(s.length()==0){
            Toast.makeText(RateActivity.this, "请输入数据", Toast.LENGTH_SHORT).show();
//            Snackbar.make(input,"请输入数据",Snackbar.LENGTH_SHORT).show();
            return;
        }
        float inp = Float.parseFloat(s);
        float r = 0.0f;
        if(btn.getId()==R.id.btn_dollar){
            r = inp * dollarrate;
        }else if(btn.getId()==R.id.btn_euro){
            r= inp * eurorate;
        }else{
            r = inp * wonrate;
        }
        show = findViewById(R.id.tw1);
        show.setText("兑换："+r);
    }
    public void open(View btn){
        Log.i(TAG,"打开新窗口");
        Intent intent= new Intent(this,ConfigActivity.class);
        intent.putExtra("key_dollar",dollarrate);
        intent.putExtra("key_euro",eurorate);
        intent.putExtra("key_won",wonrate);
        Log.i(TAG,"openOne:dollarrate="+dollarrate);
        Log.i(TAG,"openOne:eurorate="+eurorate);
        Log.i(TAG,"openOne:wonrate="+wonrate);
//        startActivity(intent);
        startActivityForResult(intent,3);//requestCode任意整数,表示打开的是哪一个窗口
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {//resultCode表示带回来的是哪一个窗口，确定data里是什么:美元欧元还是韩元
        if(requestCode==3&&resultCode==6){
            Bundle bdl = data.getExtras();
            dollarrate = bdl.getFloat("key_dollar2",0.1f);
            eurorate = bdl.getFloat("key_euro2",0.1f);
            wonrate = bdl.getFloat("key_won2",0.1f);
            Log.i(TAG,"openOne:dollarrate="+dollarrate);
            Log.i(TAG,"openOne:eurorate="+eurorate);
            Log.i(TAG,"openOne:wonrate="+wonrate);
            //保存新的汇率数据到sharedPreferences
            SharedPreferences sp=getSharedPreferences("myrate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putFloat("dollar_rate",dollarrate);
            editor.putFloat("euro_rate",eurorate);
            editor.putFloat("won_rate",wonrate);
            editor.apply();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.mymenu,menu);
        return true;//启用菜单项
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.menu_settings){
            //事件处理
        }
        return super.onOptionsItemSelected(item);
    }

        @Override
        public void run() {
            Log.i(TAG, "run:run()....");
            Bundle bdl = new Bundle();
            Document doc = null;
            try {
                doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();
                Log.i(TAG, "RUN:title" + doc.title());
                Element table = doc.getElementsByTag("table").first();
                Elements trs = table.getElementsByTag("tr");
                trs.remove(0);
                for (Element tr : trs) {
                    Elements tds = tr.getElementsByTag("td");
                    if (tds.size() > 0) {
                        Element td1 = tds.first();
                        Element td2 = tds.last();
                        String str1 = td1.text();
                        String str2 = td2.text();
                        Log.i(TAG, "run:" + str1 + "==>" + str2);
                        if (str1.equals("美元")) {
                            bdl.putFloat("web-dollar", 100f / Float.parseFloat(str2));
                        } else if (str1.equals("欧元")) {
                            bdl.putFloat("web-euro", 100f / Float.parseFloat(str2));
                        } else if (str1.equals("韩元")) {
                            bdl.putFloat("web-won", 100f / Float.parseFloat(str2));
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            Message msg = handler.obtainMessage(5); //发送消息
//        msg.what =5;
            msg.obj = bdl;
            handler.sendMessage(msg);
            Log.i(TAG, "run:sendMessage");
        }


    private String inputStream2String(InputStream inputStream) throws IOException{
        final int bufferSize = 1024;
        final char[] buffer=new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"gb2312");
        while (true){
            int rsz=in.read(buffer,0,buffer.length);
            if(rsz<0){
                break;
            }
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }
    //从html中提取纯文本,未去除完全
    public static String StripHT(String strHtml) {
        String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
        txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
        return txtcontent;
    }
    //从html中提取纯文本
    public static String Html2Text(String inputString) {
        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_style;
        java.util.regex.Matcher m_style;
        java.util.regex.Pattern p_html;
        java.util.regex.Matcher m_html;
        try { String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签
            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签
            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签
            textStr = htmlStr;
        } catch (Exception e) {System.err.println("Html2Text: " + e.getMessage()); }
        textStr=textStr.replaceAll("[ ]+", " ");//剔除空格行
        textStr=textStr.replaceAll("(?m)^\\s*$(\\n|\\r\\n)", "");
        return textStr;// 返回文本字符串
    }
}